package com.example.daily.demo.config;



import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.mail.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

/**
 * 接收邮件配置类
 * @author tianzehua
 * @date 2020/11/11
 */
@Configuration
public class ShowMail {
    private  String id;
    // 发送时间
    private  String sendTime;
    // 发送人
    private  String toUsernames;


    // 发送主题
    private  String subject;
    // 发送内容
    private  String content;
    private MimeMessage mimeMessage = null;
    private StringBuffer bodyText = new StringBuffer(); // 存放邮件内容的StringBuffer对象
    private String dateFormat = "yy-MM-dd HH:mm"; // 默认的日前显示格式

    @Value("${mail.login.username}")
    private String mailUsername;
    @Value("${mail.login.password}")
    private String mailPassword;

    /**
     * 判断此邮件是否已读，如果未读返回false,反之返回true
     */
    public boolean isNew() throws MessagingException {
        boolean isNew = false;
        Flags flags = ((Message) mimeMessage).getFlags();
        Flags.Flag[] flag = flags.getSystemFlags();
       // System.out.println("flags的长度:　" + flag.length);
        for (int i = 0; i < flag.length; i++) {
            if (flag[i] == Flags.Flag.SEEN) {
                isNew = true;
            //    System.out.println("seen email...");
                // break;
            }
        }
        return isNew;
    }
    public ShowMail(MimeMessage mimeMessage) {
            this.mimeMessage = mimeMessage;
         //   System.out.println("创建一个ReceiveEmail对象....");
    }
    public ShowMail() {
    }

    /**
     * 　*　获得发件人的地址和姓名 　
     */
    public String getFrom() throws Exception {
        InternetAddress address[] = (InternetAddress[]) mimeMessage.getFrom();
        String from = address[0].getAddress();
        if (from == null) {
            from = "";
            System.out.println("无法知道发送者.");
        }
        String personal = address[0].getPersonal();

        if (personal == null) {
            personal = "";
            System.out.println("无法知道发送者的姓名.");
        }

        String fromAddr = null;
        if (personal != null || from != null) {
            fromAddr = personal + "<" + from + ">";
          //  System.out.println("发送者是：" + fromAddr);
        } else {
            System.out.println("无法获得发送者信息.");
        }
        return fromAddr;
    }

    /**
     * 　*　获得邮件的收件人，抄送，和密送的地址和姓名，根据所传递的参数的不同
     * 　*　"to"----收件人　"cc"---抄送人地址　"bcc"---密送人地址 　
     */
    public String getMailAddress(String type) throws Exception {
        String mailAddr = "";
        String addType = type.toUpperCase();

        InternetAddress[] address = null;
        if (addType.equals("TO") || addType.equals("CC")
                || addType.equals("BCC")) {

            if (addType.equals("TO")) {
                address = (InternetAddress[]) mimeMessage
                        .getRecipients(Message.RecipientType.TO);
            } else if (addType.equals("CC")) {
                address = (InternetAddress[]) mimeMessage
                        .getRecipients(Message.RecipientType.CC);
            } else {
                address = (InternetAddress[]) mimeMessage
                        .getRecipients(Message.RecipientType.BCC);
            }

            if (address != null) {
                for (int i = 0; i < address.length; i++) {
                    String emailAddr = address[i].getAddress();
                    if (emailAddr == null) {
                        emailAddr = "";
                    } else {
                        //System.out.println("转换之前的emailAddr: " + emailAddr);
                        emailAddr = MimeUtility.decodeText(emailAddr);
                       // System.out.println("转换之后的emailAddr: " + emailAddr);
                    }
                    String personal = address[i].getPersonal();
                    if (personal == null) {
                        personal = "";
                    } else {
                      //  System.out.println("转换之前的personal: " + personal);
                        personal = MimeUtility.decodeText(personal);
                       // System.out.println("转换之后的personal: " + personal);
                    }
                    String compositeto = personal + "<" + emailAddr + ">";
                   // System.out.println("完整的邮件地址：" + compositeto);
                    mailAddr += "," + compositeto;
                }
                mailAddr = mailAddr.substring(1);
            }
        } else {
            throw new Exception("错误的电子邮件类型!");
        }
        return mailAddr;
    }

    /**
     * 　*　获得邮件主题 　
     */
    public String getSubject() throws MessagingException {
        String subject = "";
        try {
         //  System.out.println("转换前的subject：" + mimeMessage.getSubject());
            subject = MimeUtility.decodeText(mimeMessage.getSubject());
           // System.out.println("转换后的subject: " + mimeMessage.getSubject());
            if (subject == null) {
                subject = "";
            }
        } catch (Exception exce) {
            exce.printStackTrace();
        }
        return subject;
    }


    public String getSentDate() throws Exception {
        Date sentDate = mimeMessage.getSentDate();
     //   System.out.println("发送日期 原始类型: " + dateFormat);
        SimpleDateFormat format = new SimpleDateFormat(dateFormat);
        String strSentDate = format.format(sentDate);
        //System.out.println("发送日期 可读类型: " + strSentDate);
        return strSentDate;
    }

    /**
     * 　*　获得邮件正文内容 　
     */
    public String getBodyText() {
        return bodyText.toString();
    }
    /**
     *　获得此邮件的Message-ID 　　
     */
    public String getMessageId() throws MessagingException {
        String messageID = mimeMessage.getMessageID();
    //    System.out.println("邮件ID: " + messageID);
        return messageID;
    }


    /**
     * 　　*　解析邮件，把得到的邮件内容保存到一个StringBuffer对象中，解析邮件
     * 　　*　主要是根据MimeType类型的不同执行不同的操作，一步一步的解析 　　
     */

    public void getMailContent(Part part) throws Exception {

        String contentType = part.getContentType();
        // 获得邮件的MimeType类型
        //System.out.println("邮件的MimeType类型: " + contentType);

        int nameIndex = contentType.indexOf("name");

        boolean conName = false;

        if (nameIndex != -1) {
            conName = true;
        }

       // System.out.println("邮件内容的类型:　" + contentType);

        if (part.isMimeType("text/plain") && conName == false) {
            // text/plain 类型
            bodyText.append((String) part.getContent());
        } else if (part.isMimeType("text/html") && conName == false) {
            // text/html 类型
            bodyText.append((String) part.getContent());
        } else if (part.isMimeType("multipart/*")) {
            // multipart/*
            Multipart multipart = (Multipart) part.getContent();
            int counts = multipart.getCount();
            for (int i = 0; i < counts; i++) {
                getMailContent(multipart.getBodyPart(i));
            }
        } else if (part.isMimeType("message/rfc822")) {
            // message/rfc822
            getMailContent((Part) part.getContent());
        } else {

        }
    }



    public   List<ShowMail>   imapReceive()  {
        // 准备连接服务器的会话信息
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "imap");
        props.setProperty("mail.imap.host", "imap.qiye.163.com");
        props.setProperty("mail.imap.port", "143");

        // 创建Session实例对象
        Session session = Session.getInstance(props);

        // 创建IMAP协议的Store对象
        Store store = null;
        try {
            store = session.getStore("imap");
            // 连接邮件服务器
            store.connect(mailUsername, mailPassword);

            // 获得收件箱
            Folder folder = store.getFolder("INBOX");
            // 以读写模式打开收件箱
            folder.open(Folder.READ_WRITE);

            // 获得收件箱的邮件列表
            Message[] message = folder.getMessages();

            // 打印不同状态的邮件数量
            System.out.println("收件箱中共" + message.length + "封邮件!");
            System.out.println("收件箱中共" + folder.getUnreadMessageCount() + "封未读邮件!");
            System.out.println("收件箱中共" + folder.getNewMessageCount() + "封新邮件!");
            System.out.println("收件箱中共" + folder.getDeletedMessageCount() + "封已删除邮件!");
            ShowMail re = null;
            List<ShowMail> showMails = new ArrayList<>();
            // 解析邮件
            for (int i = 0; i < message.length; i++) {
                re = new ShowMail((MimeMessage) message[i]);
                if (!re.isNew()){
                    re.setSubject(re.getSubject());
                    re.setContent(re.getBodyText());
                    re.setToUsernames(re.getFrom());
                    showMails.add(re);
                    // 标记为已读
                    re.mimeMessage.setFlag(Flags.Flag.SEEN, true);
                }
            }
            // 关闭资源
            folder.close(false);
            store.close();
            return showMails;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getSendTime() {
        return sendTime;
    }

    public void setSendTime(String sendTime) {
        this.sendTime = sendTime;
    }

    public String getToUsernames() {
        return toUsernames;
    }

    public void setToUsernames(String toUsernames) {
        this.toUsernames = toUsernames;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}
